<?php
/**
 * Created by PhpStorm.
 * User: taj
 * Date: 14-10-16
 * Time: 下午11:20
 */

class Controller_Returnstock extends Controller_Admin {
    /**
     *退件处理权限
     *
     */
    public function before()
    {
        try {
            ACL::Required('create returnstock');
        } catch ( HTTP_Exception_403 $e ) {
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect ( URL::base (true) );
        }
        parent::before();
    }

    /**
     *退件默认界面
     *
     */
    public function action_index()
    {
        $this->title = __('订单扫描回库-重新入良品仓');
        $warehouseid = Kohana::$config->load('warehouse')->warehouse_id;
        if(isset($_GET['orderid'])){
        $order_id = isset($_GET['orderid'])?trim($_GET['orderid']):'';

        $user_id = User::active_user()->id;
        if($order_id==''){
            message::error('扫描的订单号不能为空');

        }else{
            if(substr($order_id,0,1)=='e' ||substr($order_id,0,1)=='E'){
                if(strlen($order_id) >13){
                    $order_id2 = substr($order_id,1,13);
                }else{
                    $order_id2 = substr($order_id,1,10);
                }
            }else{
                $sql_orderid = "SELECT `erp_orders_id`,`orders_status`,`orders_mail_code` FROM `erp_orders`
                WHERE orders_mail_code='".mysql_escape_string($order_id)."'
                OR orders_shipping_code = '".$order_id."'";
                $arr_orderid = DB::query(Database::SELECT,$sql_orderid)->execute('readonlyerp')->current();
                $order_id2 = intval($arr_orderid['erp_orders_id']);
            }
            //var_dump($order_id2);exit;
           // echo $order_id;
            if(empty($order_id2)){
                message::error($order_id.'该订单号格式不对，不是带E的erp订单号或其它追踪号');
            }else{


            $sql_returno = "SELECT count(0) as num FROM `returnstockorder` WHERE `order_id`=".intval($order_id2);
            $returno_num = DB::query(Database::SELECT,$sql_returno)->execute('newerp')->as_array();

                //yuqing   ---begin---
                $order_status = DB::select_array(array('erp_orders_id','orders_status'))
                    ->from('erp_orders')
                    ->where('erp_orders_id','=',intval($order_id2))
                    ->execute('readonlyerp')
                    ->as_array('erp_orders_id','orders_status');

                //yuqing   ---end ----
            if($returno_num[0]['num']>0){
                message::error($order_id.'该订单号已扫描回库，不可再次扫描回库');
            }else{
            $sql = "SELECT * FROM `deliveryorders` WHERE `order_id`=".$order_id2;
            $res = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
            if(empty($res)){
                message::error($order_id.'该订单号没有出库记录，扫描回库失败');
            }else{
                $insert_val = array();
                $sql_in = "INSERT INTO returnstockorder(add_user,add_time,order_id) VALUES
                        ('".$user_id."','".date('Y-m-d H:i:s')."','".$order_id2."')";
                $result = DB::query(Database::INSERT,$sql_in)->execute('newerp');
                if($result){
                foreach($res as $re){
                    if($re['sku']=='' ||$re['quantity']==0){
                        continue;
                    }
                    $supplier = new Service_Common();
                    $price = $supplier->get_sku_price($re['sku']);
                    $wo = ORM::factory('warehouseorder');

                    $wo->warehouseid = $warehouseid;
                    $wo->warehouse_date = date('Y-m-d H:i:s');
                    $wo->op_time = date('Y-m-d H:i:s');
                    $wo->deliveryorders_id = $re['id'];
                    $wo->sku  =$re['sku'];
                    $wo->sku_name= $re['sku_name'];
                    $wo->sku_standard = $re['sku_standard'];
                    $wo->storage_position = $re['storage_position'];
                    $wo->warehouse_quantity= $re['quantity'];
                    if($re['single_price']==0){
                        $wo->single_price = $price;
                        $wo->money = $price*$re['quantity'];
                    }else{
                        $wo->single_price = $re['single_price'];
                        $wo->money = $re['money'];
                    }

                    $wo->cost = $price*$re['quantity'];
                    $wo->remark = '未出仓库前的包裹扫描回库，订单号是'.$re['order_id'];
                    $wo->type = 80;
                    $wo->warehouse_man = $user_id;
                    $insert_val[] = $wo->save();

                    
                }
                    // yuqing 2016年5月28日 此处开始封存商品扫描核对与老erp的数据,并更改老erp状态为已打印？还是已通过？，

//                    $seal_res = Warehouse::seal_order_check_data($order_id2);
                    //yuqing 2016年5月31日 只更改状态为4

                    if(in_array($order_status[$order_id2],array(7))){
                        $update_erp_orders = Warehouse::change_erp_orders_status($order_id2);
                        if(sizeof($insert_val) > 0 && $update_erp_orders) {
                            message::success($order_id . '该订单号回库成功');
                        }else{
                            message::error($order_id . '该订单号回库失败1！');
                        }
                    }else{
                    //yuqing  end
                        if(sizeof($insert_val) > 0) {
                            message::success($order_id . '该订单号回库成功');
                        }else{
                            message::error($order_id . '该订单号回库失败2！');
                        }
                    }
                }else{
                    message::error($order_id.'该订单号回库失败3');
                }

            }
            }

        }
        }
        }
        $view=View::factory('inventory/returnstock');

        $this->response->body($view);
    }
}